<?php

if_get('/fields', function ()
{/*{{{*/
    list(
        $inputs['name'], $inputs['key'], $inputs['type'], $inputs['subject_id']
    ) = input_list(
        'name', 'key', 'type', 'subject_id'
    );

    $inputs = array_filter($inputs, 'not_null');

    $fields = dao('field')->find_all_by_column($inputs);

    return [
        'count' => count($fields),
        'fields' => array_build($fields, function ($id, $field) {
            return [
                null,
                [
                    'id' => $field->id,
                    'name' => $field->name,
                    'key' => $field->key,
                    'type' => $field->get_type_description(),
                    'subject_display' => $field->subject->display_for_fields_subject(),
                    'create_time' => $field->create_time,
                    'update_time' => $field->update_time,
                ]
            ];
        }),
    ];
});/*}}}*/

if_post('/fields/update/*', function ($field_id)
{/*{{{*/
    $name = input('name');
    $key = input('key');
    $type = input('type');

    $field = dao('field')->find($field_id);
    otherwise_error_code('FIELD_NOT_FOUND', $field->is_not_null());

    $another_field = dao('field')->find_by_name_and_key_and_type($name, $key, $type);
    otherwise_error_code('FIELD_DUPLICATED', $another_field->is_null() || $another_field->id === $field->id, [':field_id' => $another_field->id]);

    $field->subject = input_entity('subject', null, 'subject_id');
    $field->name = $name;
    $field->key = $key;
    $field->type = $type;

    return true;
});/*}}}*/

if_post('/fields/delete/*', function ($field_id)
{/*{{{*/
    $field = dao('field')->find($field_id);
    otherwise_error_code('FIELD_NOT_FOUND', $field->is_not_null());

    $field->delete();

    return true;
});/*}}}*/
